package com.zzgc.modules.service.impl;

import com.zzgc.common.dao.SchoolGradeClassDao;
import com.zzgc.common.dao.SchoolGradeDao;
import com.zzgc.common.dao.StudentDao;
import com.zzgc.common.entity.*;
import com.zzgc.common.utils.IdCardNumberMethod;
import com.zzgc.common.utils.LangUtil;
import com.zzgc.modules.controller.BaseController;
import com.zzgc.modules.controller.WsController;
import com.zzgc.modules.param.AddStudentParam;
import com.zzgc.modules.param.ExportStudentTemplate;
import com.zzgc.modules.param.ImportStudentTemplate;
import com.zzgc.modules.service.StudentService;
import org.springframework.stereotype.Service;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.PageRequest;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.ParseException;
import java.time.LocalDate;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 学校学生(Student)表服务实现类
 *
 * @author makejava
 * @since 2022-12-05 14:32:14
 */
@Service("studentService")
public class StudentServiceImpl implements StudentService {
    @Resource
    private StudentDao studentDao;
    @Resource
    private SchoolGradeDao schoolGradeDao;
    @Resource
    private SchoolGradeClassDao schoolGradeClassDao;

    /**
     * 通过ID查询单条数据
     *
     * @param id 主键
     * @return 实例对象
     */
    @Override
    public Student queryById(Long id) {
        return this.studentDao.queryById(id);
    }

    @Override
    public List<ExportStudentTemplate> queryByPageExport(Student student) {
        return this.studentDao.queryAllByLimitExport(student);
    }

    /**
     * 分页查询
     *
     * @param student 筛选条件
     * @return 查询结果
     */
    @Override
    public List<Student> queryByPage(Student student) {
        if (student.getSYear() == null || student.getSYear().equals("")){
            student.setSYear(BaseController.getsYear() + "");
        }
        List<Student> students = this.studentDao.queryAllByLimit(student);
        long count = this.studentDao.count(student);
        if (count == 0) {
            return new ArrayList<>();
        }
        students.get(0).setTotal(count);
        return students;
    }

    @Override
    public long count(Student student) {
        return this.studentDao.count(student);
    }

    @Override
    public long countByDepartId(Long departId, String year) {
        return this.studentDao.countByDepartId(departId, year);
    }

    /**
     * 新增数据
     *
     * @param student 实例对象
     * @return 实例对象
     */
    @Override
    public Student insert(Student student) {
        // 添加学年
        student.setSYear(BaseController.getsYear() + "");
        this.studentDao.insert(student);
        return student;
    }

    // 添加单个学生, 年级, 班级表
    private Student insertStudent(String userName, Student student, Date date) {
        // 添加年级表, 判断年份年级是否重复
        SchoolGrade schoolGrade = new SchoolGrade();

        List<SchoolGrade> schoolGrades = schoolGradeDao.queryAllBy(student.getSSchoolId(), student.getSGradeName(), student.getSYear());
        if (schoolGrades.size() == 1) {
            schoolGrade = schoolGrades.get(0);
        } else {
            // 学校id
            schoolGrade.setSCreateBy(userName);
            schoolGrade.setSSchoolId(student.getSSchoolId());
            // 添加排序
            if (student.getSGradeName() != null){
                // 三年级 去除班字得到中文数字
                String s = student.getSGradeName();
                if (s.contains("高")) {
                    s = s.replaceAll("高", "");
                    schoolGrade.setSSort(LangUtil.hanZiToNum(s) + 20);
                }else {
                    s = s.replaceAll("年", "");
                    s = s.replaceAll("级", "");
                    if (!LangUtil.isNumeric(s)) {
                        schoolGrade.setSSort(LangUtil.hanZiToNum(s));
                    }else {
                        schoolGrade.setSSort(Integer.valueOf(s));
                    }
                }
            }
            schoolGrade.setSName(student.getSGradeName());
            schoolGrade.setSYear(student.getSYear());
            schoolGrade.setSCreateDate(date);
            schoolGradeDao.insert(schoolGrade);
        }

        // 添加班级表, 判断年级班级是否重复
        SchoolGradeClass schoolGradeClass = new SchoolGradeClass();
        if (student.getSClassName() != null){
            // 三班 去除班字得到中文数字
            String s = student.getSClassName().replaceAll("班", "");
            if (!LangUtil.isNumeric(s)) {
                student.setSClassName(LangUtil.hanZiToNum(s) + "班");// 修改班级为  3班
            }
        }
        List<SchoolGradeClass> schoolGradeClasses = schoolGradeClassDao.queryAllBy(schoolGrade.getSSchoolId(), student.getSClassName(), schoolGrade.getId());

        if (schoolGradeClasses.size() == 1) {
            schoolGradeClass = schoolGradeClasses.get(0);
        } else {
            // 学校id
            schoolGradeClass.setSSchoolId(schoolGrade.getSSchoolId());
            schoolGradeClass.setSCreateBy(userName);
            schoolGradeClass.setSCreateDate(date);
            // 年级id
            schoolGradeClass.setSGradeId(schoolGrade.getId());
            // 添加排序
            String s = student.getSClassName().replaceAll("班", "");
            schoolGradeClass.setSSort(Integer.valueOf(s));
            schoolGradeClass.setSName(student.getSClassName());
            schoolGradeClassDao.insert(schoolGradeClass);
        }

        // 添加学生表
//        try {
//            // 添加生日
//            student.setSBirthday(IdCardNumberMethod.getBirthDayFromIdCard(student.getSIdCard()));
//        } catch (ParseException e) {
//            throw new RuntimeException("识别身份证: " + student.getSIdCard() + "获取生日失败!");
//        }
        // 添加时间
        student.setSCreateDate(date);
        student.setSCreateBy(userName);
        // 添加年级id
        student.setSGradeId(schoolGrade.getId());
        // 添加班级id
        student.setSClassId(schoolGradeClass.getId());
        this.studentDao.insert(student);
        return student;
    }


    /**
     * 新增多条数据
     *
     * @param studentTemplate 实例对象
     * @return 实例对象
     */
    @Override
    @Transactional
    public int insertList(String userName,String userId, Long schoolId, String studentTable, List<AddStudentParam> studentTemplate) {
        float i = 0;
        for (AddStudentParam ist : studentTemplate) {
            Student student = new Student();
            student.setTableName(studentTable);
            student.setSGradeName(ist.getSGradeName());
            student.setSClassName(ist.getSClassName());
            student.setSName(ist.getSName());
            student.setSOkMirror(ist.getSOkMirror());
            // 电话号码可以重复, 如果是一家两个孩子
            student.setSMobile(ist.getSMobile());
            if (ist.getSIdCard() == null){
                throw new RuntimeException(ist.getSName() + " 的身份证号有空值!");
            }
            // 判断身份证号是否重复
            Student student1 = new Student();
            student1.setSIdCard(ist.getSIdCard());
            student1.setSYear(BaseController.getsYear() + "");
            long count = studentDao.count(student1);
            if (count > 0){
                throw new RuntimeException(ist.getSName() + " 的身份证号有重复!");
            }
            student.setSIdCard(ist.getSIdCard());
            student.setSStudentNum(ist.getSStudentNum());
            student.setSStudentId(ist.getSStudentId());
            student.setSBirthday(ist.getSBirthday());
            student.setSSex(ist.getSSex());
            // 添加表名
            //student.setTableName(studentTable);
            // 添加学年
            student.setSYear(BaseController.getsYear() + "");
            student.setSSchoolId(schoolId);
            // 开始添加学生
            insertStudent(userName, student, new Date());
            // 设置进度条0.00 - 100.00   socket连接字段是 speed_用户id
            WsController.broadcast("speed_" + userId, String.format("%.2f", i++/studentTemplate.size()*100));
        }
        return studentTemplate.size();
    }

    /**
     * 修改数据
     *
     * @param student 实例对象
     * @return 实例对象
     */
    @Override
    public Student update(Student student) {
        this.studentDao.update(student);
        return this.queryById(student.getId());
    }

    /**
     * 通过主键删除数据
     *
     * @param id 主键
     * @return 是否成功
     */
    @Override
    public boolean deleteById(Long id) {
        return this.studentDao.deleteById(id) > 0;
    }
}
